package com.tian.controller;

import com.tian.common.CommonResult;
import com.tian.dto.AuthLoginDto;
import com.tian.exception.BusinessException;
import com.tian.exception.ValidException;
import com.tian.service.AbstractLoginService;
import com.tian.service.LoginService;
import com.tian.util.JwtGeneratorUtil;
import com.tian.util.RedisConstantPre;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * {@code @description:}  用户登录token获取和验证
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-04-07 16:42
 * {@code @version:} 1.0
 */
@RestController
@RequestMapping("/token")
public class TokenController {

    @Resource
    private RedissonClient redissonClient;
    @GetMapping("/valid")
    public CommonResult<String> validToken(@RequestParam("token") String token) {
        if (StringUtils.isBlank(token)) {
            throw new ValidException("token为空");
        }
        try {
            Claims claims = JwtGeneratorUtil.parseToken(token);
            RBucket<String> bucketToken = redissonClient.getBucket(RedisConstantPre.TOKEN_PRE + token);
            // 判断redis中是否存在token 如果再新的一端被挤掉，如果再使用老的token去redis中查询不到，则返回token已过期
            if(bucketToken.get() == null){
                return CommonResult.failed("token已过期");
            }
            return CommonResult.success(claims.get("uid").toString());
        } catch (ExpiredJwtException e) {
            return CommonResult.failed("token已过期");
        } catch (SignatureException e) {
            return CommonResult.failed("签名校验失败");
        }
    }
}
